const fs = require('fs');
const { pool } = require('../../db/index');
const Router = require('koa-router');
const router = new Router();
const svgCaptcha = require('svg-captcha');
const users = [
    {
        username: 'admin',
        password: '123456',
        securityQuestions: [
            '您最喜欢的颜色是什么？',
            '您的宠物叫什么名字？'
        ],
        securityAnswers: ['蓝色', '小白']
    }
];

// 生成验证码
router.get('/api/captcha', async (ctx) => {
    const captcha = svgCaptcha.create();
    ctx.session.captcha = captcha.text;
    ctx.type = 'image/svg+xml';
    ctx.body = captcha.data;
});

// 登录
router.post('/api/login', async (ctx) => {
    try {
        const { username, password, captcha } = ctx.request.body;
        const user = users.find(u => u.username === username && u.password === password);
        if (user) {
            // 校验验证码
            if (captcha && captcha.toUpperCase() === ctx.session.captcha.toUpperCase()) {
                ctx.body = { success: true, message: '登录成功' };
            } else {
                ctx.body = { success: false, message: '验证码错误' };
            }
        } else {
            ctx.body = { success: false, message: '用户名或密码错误' };
        }
    } catch (error) {
        ctx.status = 500;
        ctx.body = { error: '接口请求失败' };
    }
});

// 安全验证
router.post('/api/verifySecurityAnswers', async (ctx) => {
    try {
        const { username, answers } = ctx.request.body;
        const user = users.find(u => u.username === username);
        if (user) {
            const isCorrect = user.securityAnswers.every((answer, index) => answer === answers[index]);
            if (isCorrect) {
                ctx.body = { success: true, message: '安全问题验证通过' };
            } else {
                ctx.body = { success: false, message: '安全问题答案错误' };
            }
        } else {
            ctx.body = { success: false, message: '用户不存在' };
        }
    } catch (error) {
        ctx.status = 500;
        ctx.body = { error: '接口请求失败' };
    }
});
// 注册接口
router.post('/api/register', async (ctx) => {
    const { username, password } = ctx.request.body;

    // 简单的输入验证
    if (!username || !password) {
        ctx.status = 400;
        ctx.body = {
            success: false,
            message: '用户名和密码不能为空'
        };
        return;
    }
    try {
        // 插入用户数据到数据库
        const [result] = await pool.execute('INSERT INTO user (username, password) VALUES (?, ?)', [username, password]);

        ctx.status = 200;
        ctx.body = {
            success: true,
            message: '注册成功',
            userId: result.insertId
        };
    } catch (error) {
        // 处理数据库插入错误，例如用户名已存在
        if (error.code === 'ER_DUP_ENTRY') {
            ctx.status = 409;
            ctx.body = {
                success: false,
                message: '用户名已存在'
            };
        } else {
            console.error('注册时数据库出错:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '注册失败，请稍后重试'
            };
        }
    }
});

module.exports = router;